package edu.cth.speedapp.student;

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import edu.cth.speedapp.Constants;
import edu.cth.speedapp.R;
import edu.cth.speedapp.asynctasks.HTTPAsyncTask;
import edu.cth.speedapp.asynctasks.ITaskCallback;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class StudentHelp extends Fragment implements ITaskCallback, OnClickListener {
	private String roomName;
	private String deviceUuid;
	private View progress;
	
	private Timer timer;
	private EditText nameEditText;
	private EditText messageEditText;
	private TextView infoText;
	private Button button;
	
	private boolean inQueue = false;
	
	private boolean firstAlertShown = false;
	private Vibrator vibrator;
	private MediaPlayer firstSound;
	
	private static final String PREFS_STUDENT_NAME = "edu.cth.speedapp.student.StudentHelp.studentName";
	
	
	public StudentHelp(String roomName, String deviceUuid) {
		super();
		this.deviceUuid = deviceUuid;
		this.roomName = roomName;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		inflater.inflate(R.layout.fragment_student_help , container);
		progress = getActivity().findViewById(R.id.helpProgress);
		progress.setVisibility(View.INVISIBLE);
		
		nameEditText = (EditText) getActivity().findViewById(R.id.helpNameEditText);
		messageEditText = (EditText) getActivity().findViewById(R.id.helpMessageEditText);
		button = (Button) getActivity().findViewById(R.id.helpButton);
		button.setOnClickListener(this);
		infoText = (TextView) getActivity().findViewById(R.id.helpQueueInfo);
		infoText.setVisibility(View.INVISIBLE);
		
		
		//First in line alert feedback!
		vibrator = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
		//Sound on scanning a qr code
		firstSound = MediaPlayer.create(getActivity(), Settings.System.DEFAULT_NOTIFICATION_URI);
        OnCompletionListener ocl = new OnCompletionListener() {
			
			public void onCompletion(MediaPlayer mp) {
				return;
			}
		};
		firstSound.setOnCompletionListener(ocl);
		firstSound.setLooping(true);	
		
		
		//Recover student name
		 SharedPreferences settings = getActivity().getSharedPreferences(Constants.SHARED_PREFS_NAME, 0);
        String roomNamePrefs = settings.getString(PREFS_STUDENT_NAME, "");
        nameEditText.setText(roomNamePrefs);
		
		return super.onCreateView(inflater, container, savedInstanceState);
		
		
		
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		Log.d("studenthelp", "mytag: onActivityCreated");
		
	}
	@Override
	public void onStart() {
		super.onStart();
		Log.d("studenthelp", "mytag: onStart");
	}

	public void httpTaskCallback(String results) {
		errorToast(results);
		if(results.contains("In queue position")){
			Scanner scan = new Scanner(results);
			scan.nextLine();
			int queuePos = Integer.parseInt(scan.nextLine());
			
			infoText.setText((queuePos-1) + " people in front of you.");
			setInqueue(true);
			if(!firstAlertShown && queuePos == 1){
				firstAlertShown = true;
				startVibrate();
				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setMessage("It's your turn!")
				       .setCancelable(false)
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                stopVibrate();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
		}else if(results.contains("In queue")){
			//Result from added to queue
			progress.setVisibility(View.INVISIBLE);
			button.setEnabled(true);
			infoText.setText("Entering queue...");
			firstAlertShown = false;

			setInqueue(true);
		}else if(results.contains("User is not in queue")){

			setInqueue(false);
		}else if(results.contains("Deleted from queue")){
			progress.setVisibility(View.INVISIBLE);

			setInqueue(false);
		}
		else{

			Log.d("tag", "Weird server response: " + results);
		}
		
	}
	private void errorToast(String msg){
		if(getActivity() != null){
			Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void startVibrate(){
		long[] pattern = { 0,//no delay
				1000, //bzzz
				2000 //silent
				};
		 
		// The "0" means to repeat the pattern starting at the beginning
		vibrator.vibrate(pattern, 0);
		firstSound.start();
	}
	private void stopVibrate(){
		vibrator.cancel();
		firstSound.stop();
	}
	
	private void setInqueue(boolean inqueue){
		
		inQueue = inqueue;
		if(inQueue){
			infoText.setVisibility(View.VISIBLE);
			button.setText(R.string.leave_queue);
			messageEditText.setHint(""); //Do not show hint if there is no message
			
		}else{
			infoText.setVisibility(View.INVISIBLE);
			button.setText(R.string.get_in_queue);
			messageEditText.setHint(R.string.message);
		}
		nameEditText.setEnabled(!inQueue);
		messageEditText.setEnabled(!inQueue);
		if(!inQueue){
			firstAlertShown = false;
		}
	}
	
	@Override
	public void onResume() {
		timer = new Timer();
		try{
			timer.schedule(updateQueuePositionTask, 0, 5000);
		}
		catch(IllegalStateException e){
			
			
		}
		super.onResume();
	}
	@Override
	public void onPause() {
		super.onPause();
		timer.cancel();
        timer.purge();
        timer = null;
	}
	
	TimerTask updateQueuePositionTask = new TimerTask(){
		@Override
		public void run() {
			if(inQueue){
				updateQueuePosition();
			}
		}

		

		
	};
	
	private void updateQueuePosition() {
		new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/getPositionHelpQueue.php?roomID=" + roomName + "&&studentID=" + deviceUuid);
	}

	public void onClick(View view) {
		if(!inQueue){
			String message = messageEditText.getText().toString();
			String studentName = nameEditText.getText().toString();
			if(studentName.length() > 0){
				progress.setVisibility(View.VISIBLE);
				nameEditText.setEnabled(false);
				messageEditText.setEnabled(false);
				button.setEnabled(false);
				
				//Save student name for later
	    	    SharedPreferences settings = getActivity().getSharedPreferences(Constants.SHARED_PREFS_NAME, 0);
	    	    settings.edit().putString(PREFS_STUDENT_NAME, studentName).commit();
				
				new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/insertIntoHelpQueue.php?roomID=" + roomName + "&&studentID=" + deviceUuid + "&&message=" + message + "&&studentName=" + studentName);
			}else{
				Toast.makeText(getActivity(), "No name entered", Toast.LENGTH_LONG).show();
			}
		}else{
			progress.setVisibility(View.VISIBLE);
			new HTTPAsyncTask(this).execute(getString(R.string.baseURL) + "/removeFromHelpQueue.php?studentID=" + deviceUuid);
			
		}
		
	}
	
	
	
	
}
